<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="8" :sm="24">
              <a-form-item label="视频名称">
                <a-input v-model="queryParam.search_key" placeholder="请输入视频名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="">
                <a-button @click="$refs.table.refresh(true)" type="primary">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator flex-y-center flex-x-sb">
        <a-radio-group :value="-1">
          <a-radio-button :value="-1"> 全部 </a-radio-button>
        </a-radio-group>
        <div>
          <a-button type="primary" @click="onAdd" icon="plus">添加</a-button>
          <a-popconfirm title="确认删除所选项吗？" @confirm="handleMenuClick">
            <a-button> 批量删除 </a-button>
          </a-popconfirm>
        </div>
      </div>
      <!-- <a-divider /> -->
      <div v-show="selectedRowKeys.length" class="select-title">
        <a-alert :message="`已选择 ${selectedRowKeys.length} 项`" type="info" show-icon />
      </div>
      <s-table
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        rowKey="id"
        size="default"
        :columns="columns"
        :data="loadData"
        ref="table"
      >
        <template slot="name" slot-scope="text, record">
          <div>
            <a-row>
              <a-col :span="2">
                <img :src="record.pic_url" style="width: 50px; height: 50px; border-radius: 5px" />
              </a-col>
              <a-col :span="22">
                <div style="color: black">{{ record.title }}</div>
                <a-tooltip>
                  <template slot="title">
                    {{ record.content }}
                  </template>
                  <div class="over_fid">{{ record.content }}</div>
                </a-tooltip>
              </a-col>
            </a-row>
          </div>
        </template>
        <span slot="action" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" size="small">编辑</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确认删除该视频吗？" @confirm="handleDelete(record)">
            <a-button type="link" size="small">删除</a-button>
          </a-popconfirm>
        </span>
      </s-table>
      <!-- 添加与编辑 -->
      <a-modal
        :title="isNew ? '创建视频' : '编辑视频'"
        :width="800"
        :confirm-loading="modalLoading"
        :mask-closable="false"
        :destroy-on-close="true"
        v-model="visible"
        @ok="handleOk"
      >
        <a-form class="permission-form" :form="form">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="display: none" label="主键" hasFeedback>
            <a-input placeholder="主键" :disabled="!isNew" v-decorator="['id']" />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="标题" hasFeedback>
            <a-input
              placeholder="视频标题"
              v-decorator="['title', { rules: [{ required: true, message: '请填写视频标题' }] }]"
            />
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序" hasFeedback>
            <a-input-number
              :min="0"
              :step="1"
              placeholder="排序"
              v-decorator="['sort', { rules: [{ required: true, message: '请填写排序' }], initialValue: 0 }]"
            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="视频来源">
            <a-radio-group v-decorator="['type', { initialValue: 0 }]" :change='urlChange()'>
              <a-radio :value="0"> 源地址 </a-radio>
              <a-radio :value="1"> 腾讯 </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="视频链接" v-show='is_mp4' hasFeedback>
            <!-- <storage-select
              selectNum="1"
              type="video"
              :defaultValue="form_video_url"
              @onOk="
                (data) => {
                  this.form_video_url = data
                }
              "
            >
            </storage-select> -->
            <cyyUploadVideo
              :videoSrc="form_video_url"
              @uploadSuccess="e => { form_video_url = e.data }"
              @deleteVideo="
                () => {
                  form_video_url = ''
                }
              "
            ></cyyUploadVideo>
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="视频地址" v-show='!is_mp4' hasFeedback>
            <a-input
              placeholder="视频地址"
              v-decorator="['url']"

            />
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="封面图">
            <!-- <storage-select
              selectNum="1"
              type="image"
              :defaultValue="form_pic_url"
              @onOk="
                (data) => {
                  this.form_pic_url = data
                }
              "
            >
            </storage-select> -->
            <cyyUploadImg
              @uploadSuccess="
                (e) => {
                  form_pic_url = e.data
                } 
              "
              @deleteImg="form_pic_url = ''"
              :imgSrc="form_pic_url"
            >
            </cyyUploadImg>
            <!-- <a-input
              placeholder="封面图"
              allow-clear
              v-decorator="['pic_url', { rules: [{required: true, message: '请填写封面图链接'}], getValueFromEvent: pic_url_change }]"
            >
              <a-icon
                slot="addonAfter"
                type="upload"
                @click="uploadImage()"
              />
            </a-input>
            <img
              width="100px"
              :src="form_pic_url"
              v-if="form_pic_url"
              alt=""
            /> -->
          </a-form-item>
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="视频详情">
            <a-textarea
              v-decorator="['content', { rules: [{ required: true, message: '请填写视频详情' }] }]"
              placeholder="请填写视频详情"
              allow-clear
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import pick from 'lodash.pick'
import { STable } from '@/components'
import { createVideo, getVideoList, editVideo, delVideo, videoDels } from '@/api/content'
import { cyyUploadVideo, cyyUploadImg } from '@/components/CyyUi/index'

const STATUS = {
  1: '显示',
  0: '不显',
}

const columns = [
  {
    title: 'ID',
    width: 120,
    dataIndex: 'id',
  },
  {
    title: '名称',
    width: 300,
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '排序',
    width: 150,
    dataIndex: 'sort',
    sorter: (a, b) => a.sort - b.sort,
  },
  {
    title: '操作',
    width: 80,
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'VideoList',
  components: {
    STable,
    cyyUploadVideo,
    cyyUploadImg,
  },
  data() {
    return {
      selectedRowKeys: [],
      isNew: false,
      visible: false,
      form_pic_url: '',
      form_video_url: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      form: this.$form.createForm(this),
      // 表头
      columns,
      // 权限树
      permissionTree: [],
      modalLoading: false,
      defaultCheckedKeys: [],
      statusSelectValue: { key: '1', label: '显示' },
      // 查询条件参数
      queryParam: {
        search_key: null,
        search_is_show: null,
      },
      //切换type
      is_mp4:true,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        Object.assign(parameter, this.queryParam)
        return getVideoList(parameter).then((res) => {
          console.log('getVideoList', res)
          return res.data
        })
      },
    }
  },
  filters: {
    statusFilter(key) {
      return STATUS[key]
    },
  },
  created() {
    console.log(this.form);
  },
  mounted(){

  },
  methods: {
    urlChange() {
      this.changeType();
    },
    changeType(){
      let that = this;
      this.form.validateFields((err, values) => {
        that.is_mp4 = values.type !== 1;
      })
    },
    onSelectChange(val) {
      this.selectedRowKeys = val
    },
    pic_url_change(e) {
      if (!e || !e.target) {
        return e
      }
      this.form_pic_url = e.target.value
      console.log(this.form_pic_url)
      return e.target.value
    },
    video_url_change(e) {
      if (!e || !e.target) {
        return e
      }
      this.form_video_url = e.target.value
      console.log(this.form_video_url)
      return e.target.value
    },
    handleEdit(record) {
      this.isNew = false
      this.visible = true
      this.$nextTick(() => {
        record.type = parseInt(record.type)
        this.form_pic_url = record.pic_url
        this.form_video_url = record.url
        this.form.setFieldsValue(pick(record, ['sort', 'title', 'id', 'pic_url', 'content', 'type', 'url']))
        console.log(this.form.getFieldsValue(),1212121212);
        this.changeType();
      })

    },
    resetQueryParams() {
      Object.assign(this.queryParam, {
        search_key: null,
        search_is_show: null,
      })
      this.$refs.table.refresh(true)
    },
    handleOk(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (err) {
          console.log(err)
          return false
        }
        console.log(values);
        Object.assign(values, {
          pic_url: this.form_pic_url,
          url: this.form_video_url,
        })
        this.modalLoading = true
        if (this.isNew) {
          createVideo(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('视频创建成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        } else {
          editVideo(values)
            .then((res) => {
              console.log(res)
              this.modalLoading = false
              if (res.code !== 0) {
                this.$error({
                  content: res.msg,
                })
              } else {
                this.$message.success('视频编辑成功！')
                this.visible = false
                this.$refs.table.refresh()
              }
            })
            .catch((err) => {
              this.$message.error(err.message)
              this.modalLoading = false
            })
        }
      })
    },
    onAdd() {
      this.isNew = true
      this.visible = true
      this.form_pic_url = ''
      this.form_video_url = ''
      this.defaultCheckedKeys = []
    },
    handleDelete: function (record) {
      const hide = this.$message.loading('删除中...', 0)
      delVideo({
        key: record.id,
      })
        .then((res) => {
          hide()
          if (res.code === 0) {
            this.$message.success('视频删除成功！')
            this.$refs.table.refresh()
          } else {
            this.$error({
              content: res.msg,
            })
          }
        })
        .catch((err) => {
          hide()
          this.$message.error(err.message)
        })
    },
    uploadVideo() {
      console.log('上传视频')
      // this.$message.info('uploadvideo342323')
    },
    // 批量操作
    async handleMenuClick() {
      if (!this.selectedRowKeys.length) return

      try {
        const res = await videoDels({ id: this.selectedRowKeys, status: 1 })
        if (res.code != 0) throw res
        this.selectedRowKeys = []
        this.$refs.table.refresh()
        this.$message.success(res.msg)
      } catch (res) {
        this.$message.error(res.msg || '服务器出错')
      }
    }
  },
}
</script>

<style lang="less" scoped>
.over_fid {
  width: 500px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
</style>
